    /*
 * Copyright (c) 2022, yifengling0. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. No personal names or organizations' names associated with the
 *    Atomthreads project may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE ATOMTHREADS PROJECT AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <Arduino.h>
#include <string.h>
#include "debug.h"
#include "syslog.h"
#define ATOM_NONE_STANDARDIO
#include "drv_pin.h"



#define _esp32_PIN(index, gpio, info) \
    {                             \
        index, gpio, info \
    }

struct pin_index
{
    int index;
    int gpio;
    const char *comment;
};

static struct pin_index pins[] = 
{
    _esp32_PIN(18, 9 , "GNSS_RST_N"),
    _esp32_PIN(21, 12, "LED1"),
    _esp32_PIN(22, 13, "LED2"),
    _esp32_PIN(10, 17, "BEEP"),
};


#define ITEM_NUM(items) sizeof(items) / sizeof(items[0])
static struct pin_index *get_pin(int pin)
{
    for (int i = 0; i < ITEM_NUM(pins); i++) {
        if (pins[i].index == pin) {
            return (&pins[i]);
        }
    }

    return NULL;
};


int  esp32_read( const Pin* dev, int pin )
{
    int value;
    const struct pin_index *index;

    index = get_pin(pin);
    if (index == NULL)
    {
        SYSLOG(LOG_WARNING, "pin no %d not found!", pin);
        return NG;
    }

    value = digitalRead(index->gpio);
    
    if(value == HIGH) return PIN_HIGH;
    else return PIN_LOW;
}


void esp32_write( const Pin* dev, int pin, int value )
{
    const struct pin_index *index;

    index = get_pin(pin);
    if (index == NULL)
    {
        SYSLOG(LOG_WARNING, "pin no %d not found!", pin);
        return;
    }


    digitalWrite(index->gpio, value);
}

void esp32_toggle( const Pin* dev, int pin)
{
    const struct pin_index *index;

    index = get_pin(pin);
    if (index == NULL)
    {
        SYSLOG(LOG_WARNING, "pin no %d not found!", pin);
        return;
    }

    digitalWrite(index->gpio,!digitalRead(index->gpio));
}

void esp32_list(const Pin* dev)
{
    KPrint("GPIO list : \r\n");
    for (int i = 0; i < sizeof(pins)/sizeof(pins[0]); i++) {
        KPrintf("  %02d : %s\r\n", pins[i].index, pins[i].comment);
    }
}

void esp32_mode( const Pin* dev, int pin, int mode)
{
    struct pin_index *index;
    int pin_mode = OUTPUT;

    index = get_pin(pin);
    if (index == NULL)
    {
        SYSLOG(LOG_WARNING, "pin no %d not found!", pin);
        return;
    }

     if (mode == PIN_MODE_OUTPUT)
     {
         /* output setting */
         pin_mode = OUTPUT;
     }
     else if (mode == PIN_MODE_INPUT)
     {
         pin_mode = INPUT;
     }
     else if (mode == PIN_MODE_INPUT_PULLUP)
     {
        pin_mode = INPUT_PULLUP;
     }
     else if (mode == PIN_MODE_INPUT_PULLDOWN)
     {
        pin_mode = INPUT_PULLDOWN;
     }
     else if (mode == PIN_MODE_OUTPUT_OD)
     {
        pin_mode = OUTPUT_OPEN_DRAIN;
     }else if(mode == PIN_MODE_OD)
     {
        pin_mode = OPEN_DRAIN;
     }

    SYSLOG(LOG_DEBUG, "pinmode %d %d %d", index->gpio, mode, pin_mode);

    pinMode(index->gpio, pin_mode);
}

// 定义一个存储中断回调的结构
typedef struct {
    void (*callback)(void *args); // 中断处理函数
    void *args;                  // 传递给回调函数的参数
    int mode;
} InterruptHandler;

// 为每个 GPIO 管脚保存中断处理函数
static InterruptHandler interruptHandlers[40]; // ESP32 最多有 40 个 GPIO

static void IRAM_ATTR gpioInterruptHandler(void *args) {
    // 从参数中获取 pin
    int pin = (int)args;

    // 检查是否有有效的回调
    if (interruptHandlers[pin].callback) {
        interruptHandlers[pin].callback(interruptHandlers[pin].args);
    }
}

/**
 * @brief Convert Atomthreads pin irq mode to Arduino pin irq mode.
 */
static int esp32_arduino_mode(int mode)
{
    int irq_mode;
    
    switch(mode){
        case PIN_IRQ_MODE_RISING:
            irq_mode = RISING;
            break;
        case PIN_IRQ_MODE_FALLING:
            irq_mode = FALLING;
            break;
        case PIN_IRQ_MODE_RISING_FALLING:
            irq_mode = CHANGE;
            break;
        default:
            irq_mode = CHANGE;
            break;
    }

    return irq_mode;
}

// esp32_attach_irq 实现
static int esp32_attach_irq(const Pin *dev, int pin, int mode, void (*hdr)(void *args), void *args) {
    if (pin < 0 || pin >= 40) {
        return -ATOM_ERROR; // 无效的 pin
    }

    // 保存中断处理函数和参数
    interruptHandlers[pin].callback = hdr;
    interruptHandlers[pin].args = args;
    interruptHandlers[pin].mode = esp32_arduino_mode(mode);

    // 设置中断模式和回调
    pinMode(get_pin(pin)->gpio, INPUT); // 确保引脚已配置为输入
    attachInterruptArg(get_pin(pin)->gpio, gpioInterruptHandler, (void *)pin, mode);

    return ATOM_OK;
}

// esp32_detach_irq 实现
static int esp32_detach_irq(const Pin *dev, int pin) {
    if (pin < 0 || pin >= 40) {
        return -ATOM_ERROR; // 无效的 pin
    }

    // 禁用中断
    detachInterrupt(get_pin(pin)->gpio);

    // 清除保存的处理函数和参数
    interruptHandlers[pin].callback = nullptr;
    interruptHandlers[pin].args = nullptr;

    return ATOM_OK;
}

// esp32_irq_enable 实现
static int esp32_irq_enable(const Pin *dev, int pin, int enabled) {
    if (pin < 0 || pin >= 40) {
        return -1; // 无效的 pin
    }

    if (enabled) {
        // 重新启用中断
        attachInterruptArg(get_pin(pin)->gpio, gpioInterruptHandler, (void *)pin, interruptHandlers[pin].mode);
    } else {
        // 禁用中断
        detachInterrupt(get_pin(pin)->gpio);
    }

    return ATOM_OK;
}


static struct PinOps _pin_ops = {
    esp32_read,
    esp32_write,
    esp32_toggle,
    esp32_mode,
    esp32_list,
    esp32_attach_irq,
    esp32_detach_irq,
    esp32_irq_enable
};


void Esp32PinCreate(void)
{
    PinCreate("pin", &_pin_ops);
    SYSLOG(LOG_INFO, "pin module initlized");
}